package com.example.demo.service;

import java.util.HashMap;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.example.demo.scheduler.RobBookingScheduler;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 杜云山
 * @date 22/06/01
 */
@Slf4j
@Service
public class BookService {

    private final RestTemplate restTemplate;

    public BookService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void bookRoom(OrderTicketBody orderTicketBody, String cookieValue, String name, String productName) {

        String cookie = RobBookingScheduler.COOKIE_NAME + "=" + cookieValue;

        HttpHeaders httpHeaders = new HttpHeaders();
///           httpHeaders.put(HttpHeaders.COOKIE, Collections.singletonList(cookie));
        httpHeaders.add(HttpHeaders.COOKIE, cookie);

        HttpEntity<Object> httpEntity = new HttpEntity<>(orderTicketBody, httpHeaders);

        try {

            log.info("---发起请求 \t 账号: {} \t 产品: {}", name, productName);
            ResponseEntity<String> response = restTemplate.exchange(
                RobBookingScheduler.ORDER_URL,
                HttpMethod.POST,
                httpEntity,
                String.class,
                new HashMap<String, String>(0)
            );

            log.info("---结果返回 \t 账号: {} \t 产品: {} \t 结果: {}", name, productName, response.getBody());
        } catch (RestClientException e) {
            log.warn("---结果异常 \t 账号: {} \t 产品: {}", name, productName, e);
        }
    }

}
